package com.adnaan.backend.controller.admin;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.adnaan.backend.common.annotation.RestControllerMapping;
import com.adnaan.backend.common.model.PageParams;
import com.adnaan.backend.common.model.Result;
import com.adnaan.backend.entity.SysRole;
import com.adnaan.backend.entity.SysUser;
import com.adnaan.backend.entity.dto.OptionDto;
import com.adnaan.backend.entity.vo.UpdatePasswordVo;
import com.adnaan.backend.service.SysRoleService;
import com.adnaan.backend.service.SysUserService;
import com.adnaan.backend.utils.PasswordUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.Map;

/**
 * author: adnaan
 * create: 2025-01-05 15:41
 * Description:
 */
@RestControllerMapping("/user")
@Tag(name = "用户管理", description = "用户管理")
@ApiSupport(author = "adnaan", order = 2)
public class SysUserController {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysRoleService sysRoleService;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @GetMapping("/info/{id}")
    @ApiOperationSupport(order = 1)
    @Operation(summary = "通过ID查询单条数据")
    public Result<SysUser> getById(@PathVariable Integer id) {
        return Result.success(sysUserService.getById(id));
    }

    /**
     * 分页查询
     *
     * @param pageParams 分页对象
     * @return 查询结果
     */
    @PostMapping("/page")
    @ApiOperationSupport(order = 2)
    @Operation(summary = "分页查询")
    public Result<Page<SysUser>> pageQuery(@RequestBody PageParams<SysUser> pageParams) {
        SysUser params = pageParams.getParams();
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.like(StrUtil.isNotBlank(params.getUsername()), SysUser::getUsername, params.getUsername());
        lqw.like(StrUtil.isNotBlank(params.getNickname()), SysUser::getNickname, params.getNickname());
        lqw.like(StrUtil.isNotBlank(params.getPhone()), SysUser::getPhone, params.getPhone());
        lqw.like(StrUtil.isNotBlank(params.getEmail()), SysUser::getEmail, params.getEmail());
        Page<SysUser> page = sysUserService.page(pageParams.getPage(), lqw);
        // 查询用户的角色
        page.getRecords().forEach(item -> {
            item.setRoles(sysUserService.getRoles(item.getId()));
        });
        return Result.success(page);
    }

    /**
     * 角色列表
     *
     * @return 实例对象
     */
    @GetMapping("/roleList")
    @ApiOperationSupport(order = 2)
    @Operation(summary = "角色列表")
    public Result<List<OptionDto>> roleList() {
        QueryWrapper<SysRole> lqw = new QueryWrapper<>();
        lqw.select("name AS label", "id AS value");
        List<Map<String, Object>> maps = sysRoleService.listMaps(lqw);
        List<OptionDto> data = BeanUtil.copyToList(maps, OptionDto.class);
        return Result.success(data);
    }

    /**
     * 新增数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */
    @PostMapping("/insert")
    @ApiOperationSupport(order = 3)
    @Operation(summary = "新增数据")
    public Result<Boolean> add(@RequestBody SysUser sysUser) {
        String salt = RandomUtil.randomString(16);
        sysUser.setSalt(salt);
        String password = sysUser.getPassword();
        String encrypt = PasswordUtils.encrypt(password, salt);
        sysUser.setPassword(encrypt);
        if (sysUserService.save(sysUser)) {
            return insertUserRole(sysUser);
        }
        return Result.error();
    }

    /**
     * 更新数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */
    @PostMapping("/update")
    @ApiOperationSupport(order = 4)
    @Operation(summary = "更新数据")
    public Result<Boolean> edit(@RequestBody SysUser sysUser) {
        sysUserService.deleteRoles(sysUser.getId());
        if (sysUserService.updateById(sysUser)) {
            //传入的roles为用户所有的角色，需要更新用户的角色，需要先删除用户的角色，再添加用户的角色
            return insertUserRole(sysUser);
        }
        return Result.error();
    }

    private Result<Boolean> insertUserRole(SysUser sysUser) {
        List<OptionDto> roles = sysUser.getRoles();
        if (roles != null && !roles.isEmpty()) {
            List<String> roleIds = roles.stream().map(OptionDto::getValue).toList();
            sysUserService.insertRoles(sysUser.getId(), roleIds);
        }
        return Result.success();
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @GetMapping("/delete/{id}")
    @ApiOperationSupport(order = 5)
    @Operation(summary = "通过主键删除数据")
    public Result<Boolean> deleteById(@PathVariable Long id) {
        if (sysUserService.removeById(id)) {
            return Result.success();
        }
        return Result.error();
    }

    /**
     * 重置密码
     *
     * @param id 主键
     */
    @GetMapping("/resetPassword/{id}")
    @ApiOperationSupport(order = 6)
    @Operation(summary = "重置密码")
    public Result<Boolean> resetPassword(@PathVariable Long id) {
        SysUser sysUser = sysUserService.getById(id);
        String salt = RandomUtil.randomString(16);
        sysUser.setSalt(salt);
        String encrypt = PasswordUtils.encrypt("123456", salt);
        sysUser.setPassword(encrypt);
        if (sysUserService.updateById(sysUser)) {
            return Result.success();
        }
        return Result.error();
    }

    /**
     * 修改密码
     */
    @PostMapping("/updatePassword")
    @ApiOperationSupport(order = 7)
    @Operation(summary = "修改密码")
    public Result<Boolean> updatePassword(@RequestBody UpdatePasswordVo updatePasswordVo) {
        Long id = StpUtil.getLoginIdAsLong();
        SysUser sysUser = sysUserService.getById(id);
        String oldPassword = updatePasswordVo.getOldPassword();

        String salt = sysUser.getSalt();
        String encrypt = PasswordUtils.encrypt(oldPassword, salt);
        if (!encrypt.equals(sysUser.getPassword())) {
            return Result.error("旧密码错误");
        }

        String newPassword = updatePasswordVo.getNewPassword();
        String confirmPassword = updatePasswordVo.getConfirmPassword();

        if (!newPassword.equals(confirmPassword)) {
            return Result.error("两次密码不一致");
        }
        String newPasswordEncrypt = PasswordUtils.encrypt(newPassword, salt);
        sysUser.setPassword(newPasswordEncrypt);

        return Result.success(sysUserService.updateById(sysUser));
    }
}
